package com.jinpeng.huobikline.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.jinpeng.huobikline.common.JsonUtils;
import com.jinpeng.huobikline.common.RedisUtils;
import com.jinpeng.huobikline.entity.DataDTO;
import com.jinpeng.huobikline.entity.HuoBiDto;
import com.jinpeng.huobikline.entity.KlineVo;
import com.jinpeng.huobikline.service.KlineServices;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class KlineController {
    @Resource
    private RedisUtils redisUtils;

    @Resource
    private KlineServices klineServices;

    @GetMapping("/market/getKline/history")
    public Object getKlineHistory(String symbol,String resolution,Integer from,Integer to){
        String s1 = symbol.toLowerCase().replace("_", "") + ":" + resolution + ":kline";
        Map updateKline =  redisUtils.hmget(s1+":update");
        if (updateKline.size()>0){
            //更新kline
            redisUtils.hmset(s1,updateKline);
        }
        Map o =  redisUtils.hmget(s1);
        List<DataDTO> result = new ArrayList<>();
        List<String> result4 = (List<String>) o.values().stream().collect(Collectors.toList());
        for (String s: result4) { JsonUtils.toBean(s,DataDTO.class); }
        for (int i = 0; i <result4.size() ; i++) { result.add(JsonUtils.toBean(result4.get(i), DataDTO.class)); }
        List<DataDTO> collect = result.stream().sorted(Comparator.comparing(DataDTO::getId)).collect(Collectors.toList());
        collect = collect.stream().filter(data-> data.getId()>from|| data.getId()<to).collect(Collectors.toList());
        KlineVo klineVo = new KlineVo();
        klineVo.setS("ok");
        klineVo.setC(collect.stream().map(DataDTO::getClose).collect(Collectors.toList()));
        klineVo.setT(collect.stream().map(DataDTO::getId).collect(Collectors.toList()));
        klineVo.setV(collect.stream().map(DataDTO::getVol).collect(Collectors.toList()));
        klineVo.setH(collect.stream().map(DataDTO::getHigh).collect(Collectors.toList()));
        klineVo.setL(collect.stream().map(DataDTO::getLow).collect(Collectors.toList()));
        klineVo.setO(collect.stream().map(DataDTO::getOpen).collect(Collectors.toList()));
        return klineVo;
    }

    @PostMapping("/market/getKline/updateKline")
    public Object updateKline(String symbol,String resolution,String timestamp,Integer updateClose){
        Map o =  redisUtils.hmget(symbol.toLowerCase()+":"+resolution+":kline");
        DataDTO o1 = JsonUtils.toBean(JsonUtils.toString(o.get(timestamp)),DataDTO.class);
        StringBuilder  stringBuffer = new StringBuilder ();
        String close = String.valueOf(o1.getClose());
        StringBuilder append = stringBuffer.append(close.split("\\.")[0]).append(".").append(RandomUtil.randomInt(9)).append(updateClose);
        o1.setClose(Double.valueOf(String.valueOf(append)));
        //StrUtil
        Map map = new HashMap();
        map.put(timestamp,JsonUtils.toString(o1));
        redisUtils.hmset(symbol.toLowerCase()+":"+resolution+":kline",map);
        redisUtils.hmset(symbol.toLowerCase()+":"+resolution+":kline:update",map);
        return o1;
    }


    @PostMapping("/market/getKline/getKline")
    public Object getKline(String symbol,String resolution,String timestamp){
        log.info("获取时间戳为：{},转换为时间为：{}",timestamp, DateUtil.date(Long.valueOf(timestamp)*1000));
        DateTime date = DateUtil.date(Long.valueOf(timestamp) * 1000);
        DateTime dateTime = DateUtil.offsetMinute(date, 5);
        String substring = String.valueOf(dateTime.getTime()).substring(0, 10);
        Map o =  redisUtils.hmget(symbol.toLowerCase()+":"+resolution+":kline");
        DataDTO o1 = null;
        try {
            Object o2 = o.get(substring);
            if (!Objects.isNull(o2)){
                o1 = JsonUtils.toBean(JsonUtils.toString(o.get(timestamp)), DataDTO.class);
            }
        } catch (Exception e) {
            log.error("获取时间戳为：{},转换为时间为：{}",timestamp, DateUtil.date(Long.valueOf(timestamp)*1000));
            e.printStackTrace();
        }
        log.info("获取时间戳为：{},转换为时间为：{},获取的数据为：{}",timestamp, DateUtil.date(Long.valueOf(timestamp)*1000),o1);
        return o1;
    }

    @PostMapping("/market/makeKline/init")
    public void init(String symbol){
        klineServices.initKline(symbol);
    }

    @PostMapping("/market/makeKline/getPrice")
    public Map getPrice(){
        HuoBiDto price = klineServices.getPrice();
        Map result = new HashMap();
        result.put("code",200);
        result.put("data",price.getData().get(0));
        result.put("msg","success");
        return result;
    }


    @GetMapping("/market/getKline/config")
    public Object symbolConfig(){
       return klineServices.symbolConfig();
    }

    @GetMapping("/market/getKline/symbol_info")
    public Object symbolInfo(String group){
        return klineServices.symbolInfo(group);
    }

}
